package com.gexin.model.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gexin.common.model.ZTree;
import com.gexin.model.system.base.BaseAdminRoleRes;
import com.jfinal.plugin.activerecord.Db;

/**
 * 业务名称:  t_admin_role_res(权限对应的资源信息) 
 */
@SuppressWarnings("serial")
public class AdminRoleRes extends BaseAdminRoleRes<AdminRoleRes> {
	public static final AdminRoleRes dao = new AdminRoleRes();
	
	public void deleteByRoleId(Integer roleid){
		Db.update("delete from  t_admin_role_res where role_id=?",roleid);
	}
	/**
	 * 根据权限组 回填权限
	 * @param roleid
	 * @return
	 */
	public List<ZTree> getRoleRes(Integer roleid){
		List<ZTree>     list = new ArrayList<ZTree>();
		if(roleid==null){
			//没有指定就加载全部
			List<AdminRes> reslist = AdminRes.dao.find("select * from t_admin_res");
			for(AdminRes res: reslist){
				ZTree tree =new ZTree(res.getId(), res.getName(), res.getPid()==null?0:res.getPid());
				if(res.getPid()!=null){
					tree.setOpen(false);
				}
				list.add(tree);
			}
		}else{
			//需要回填数据
			List<AdminRes> reslist = AdminRes.dao.find("select * from t_admin_res");
			
			//查询原来的数据
			List<AdminRoleRes>  historylist =   AdminRoleRes.dao.find("select * from  t_admin_role_res where role_id=?",roleid);
			Map<Integer,Integer>  map = new HashMap<Integer, Integer>();
			for(AdminRoleRes res: historylist){
				map.put(res.getResId(), res.getId());	
			}
			
			for(AdminRes res: reslist){
				ZTree tree =new ZTree(res.getId(), res.getName(), res.getPid()==null?0:res.getPid());
				if(res.getPid()!=null){
					tree.setOpen(false);
				}
				//以前选择过的
				if(map.get(res.getId())!=null){
					tree.setChecked(true);
				}

				list.add(tree);
			}
		}
		
		return list;
	}
	
	/**
	 * 根据权限ID查询用户关联权限数据
	 * @param roleId
	 * @return
	 */
	public List<AdminRoleRes> findByRoleId(Integer roleId) {
		return dao.find(" select * from t_admin_user_role where role_id=?",roleId);
	}
}
